import { Feature } from 'ol';
import { LineString } from 'ol/geom';

export class Arc extends Feature {
    constructor(coordinates) {
        super();
        this.coordinates = coordinates || [];
    }

    getGeometry() {
        if (this.coordinates.length < 3) {
            return null;
        }

        return new LineString(this.calculateArcPoints());
    }

    calculateArcPoints() {
        const points = [];
        const p1 = this.coordinates[0];
        const p2 = this.coordinates[1];
        const p3 = this.coordinates[2];

        // 计算圆心和半径
        const [center, radius] = this.getCircleCenterAndRadius(p1, p2, p3);
        if (!center || !radius) {
            return [p1, p2, p3];
        }

        // 计算起始角度和结束角度
        const startAngle = Math.atan2(p1[1] - center[1], p1[0] - center[0]);
        const endAngle = Math.atan2(p3[1] - center[1], p3[0] - center[0]);

        // 生成弧线点
        const segments = 100;
        let angleDiff = endAngle - startAngle;
        if (angleDiff < 0) {
            angleDiff += 2 * Math.PI;
        }

        for (let i = 0; i <= segments; i++) {
            const angle = startAngle + (angleDiff * i) / segments;
            const x = center[0] + radius * Math.cos(angle);
            const y = center[1] + radius * Math.sin(angle);
            points.push([x, y]);
        }

        return points;
    }

    getCircleCenterAndRadius(p1, p2, p3) {
        const x1 = p1[0], y1 = p1[1];
        const x2 = p2[0], y2 = p2[1];
        const x3 = p3[0], y3 = p3[1];

        const temp = x2 * x2 + y2 * y2;
        const bc = (x1 * x1 + y1 * y1 - temp) / 2.0;
        const cd = (temp - x3 * x3 - y3 * y3) / 2.0;
        const det = (x1 - x2) * (y2 - y3) - (x2 - x3) * (y1 - y2);

        if (Math.abs(det) < 1e-10) {
            return [null, null];
        }

        const centerX = (bc * (y2 - y3) - cd * (y1 - y2)) / det;
        const centerY = ((x1 - x2) * cd - (x2 - x3) * bc) / det;
        const radius = Math.sqrt(Math.pow(x1 - centerX, 2) + Math.pow(y1 - centerY, 2));

        return [[centerX, centerY], radius];
    }
}